package com.zhangkeyou.map.mapweb.handler;

import com.alibaba.fastjson.JSON;
import com.zhangkeyou.map.mapweb.domain.entity.Status;
import com.zhangkeyou.map.mapweb.util.WebUtils;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author: 张克友
 * @create: 2023-09-01 19:09
 * @description: security认证异常实现类
 **/
@Component
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint {

    /**
     * 认证失败时，抛出异常时，调用该方法
     * @param httpServletRequest
     * @param httpServletResponse
     * @param e
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        Status result = new Status(HttpStatus.UNAUTHORIZED.value(),null,"请重新登录");
        String resultStr = JSON.toJSONString(result);
        //处理异常
        WebUtils.renderString(httpServletResponse,resultStr);
    }
}
